﻿using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using VijayGande.WebParts.Classes;

namespace VijayGande.WebParts.DocumentsHyperLinksByChoiceViewWP
{
    public partial class DocumentsHyperLinksByChoiceViewWPUserControl : UserControl
    {
        #region "Implementation Summary"

        //The drop down is filled dynamically based on the choice filed name of the document library.
        //User has to set the web part properties to use this.
        //The usercontrol codebehind file ges the web part properties form the web part code (.cs) file.

        #endregion "Implementation Summary"

        //ToDo:  Work on Update pannel usage in design canvas / design mode.
        HyperLinkField hyperLinkField = new HyperLinkField();
        SPGridView gvDocumentsHyperLinks = new SPGridView();
        Label lblError = new Label();

        public string docLibDispName = String.Empty;// MDPConstants.DOCLIB_SALES_RESOURCES_DISP_NAME;
        public string docLibInternalName = String.Empty;//to build the url for the resource, //MDPConstants.DOCLIB_SALES_RESOURCES_INT_NAME;
        public string docLibraryWebSiteURL = String.Empty;
        public string choiceFieldName = String.Empty;//"ResourceType"; to fill the drop down during run time.

        SPSite site = SPContext.Current.Site;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDocumentTypeChoices();//build the drop down list values.
                lblChoiceName.Text = "<b>" + ddlChoices.SelectedItem.Text + "</b>";
                BuildDocumentsHyperLinksGrid(GetDocumentsByChoice(ddlChoices.SelectedItem.Text));
            }
        }

        protected void ddlChoices_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                BuildDocumentsHyperLinksGrid(GetDocumentsByChoice(ddlChoices.SelectedItem.Text));
                lblChoiceName.Text = ddlChoices.SelectedItem.Text;
            }
            catch (Exception ex)
            {
                Helper.ShowMessage(lblError, "Could not load User Control, Error Msg: <br />" + ex.Message + "<br/> StackTrace: " + ex.StackTrace);
                this.Controls.Add(lblError);
                return;
            }
        }

        private void BindDocumentTypeChoices()
        {
            ddlChoices.DataSource = GetDocumentTypeChoices();
            ddlChoices.DataTextField = "DocumentTypeChoiceTextField";
            ddlChoices.DataValueField = "DocumentTypeChoiceValueField";
            ddlChoices.DataBind();
        }

        DataView GetDocumentTypeChoices()
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add(new DataColumn("DocumentTypeChoiceTextField", typeof(String)));
            dataTable.Columns.Add(new DataColumn("DocumentTypeChoiceValueField", typeof(String)));

            SPList spList = null;
            using (SPSite spSite = new SPSite(docLibraryWebSiteURL + "/"))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    spList = spWeb.Lists[docLibDispName];
                    if (spList != null)
                    {
                        SPFieldChoice spFieldChoice = (SPFieldChoice)spList.Fields[choiceFieldName];
                        foreach (string strChoice in spFieldChoice.Choices)
                        {
                            dataTable.Rows.Add(Helper.Create2ColumnRow(strChoice, strChoice, dataTable));
                        }
                    }
                }
            }
            DataView dataView = new DataView(dataTable);
            return dataView;
        }

        public void BuildDocumentsHyperLinksGrid(DataView dataView)
        {
            gvDocumentsHyperLinks.AutoGenerateColumns = false;
            //gvSalesResources.HeaderRow.Visible = false;
            //string webURL = SPContext.Current.Web.Url;

            HyperLinkField hyperLinkField = new HyperLinkField();
            //hyperLinkField.HeaderText = this.lblCategoryName.Text;
            //*LinkFilename is the Field Name Holding the Url Param
            hyperLinkField.DataNavigateUrlFields = new string[] { "LinkFilename" };
            hyperLinkField.DataNavigateUrlFormatString = docLibraryWebSiteURL + "/" + docLibInternalName + "/{0}";
            hyperLinkField.DataTextField = "LinkFilename";
            gvDocumentsHyperLinks.Columns.Add(hyperLinkField);

            #region "Not in Use, may give idea on header style"

            //spGrid.HeaderRow.Visible = false;
            //spGrid.HeaderRow.CssClass = @"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\STYLES\Vj\HeaderCSS.css";
            //spGrid.HeaderRow.CssClass = ".ms-viewheadertr{display:none;}";
            //System.Web.UI.WebControls.Unit unit = new Unit(0);
            //spGrid.HeaderRow.Height = unit;

            //spGrid.HeaderRow.Cells[0].Visible = false;
            //spGrid.ShowHeader = false;

            #endregion "Not in Use, may give idea on header style"

            gvDocumentsHyperLinks.DataSource = dataView;
            gvDocumentsHyperLinks.DataBind();
            this.Controls.Add(gvDocumentsHyperLinks);
        }

        DataView GetDocumentsByChoice(string choiceFieldValue)
        {
            DataView dataView = null;
            SPQuery qryDocumentsByChoice = new SPQuery();
            qryDocumentsByChoice.Query = "<Where><Eq><FieldRef Name=" + choiceFieldName + "/><Value Type='Choice'>" + choiceFieldValue + "</Value></Eq></Where></Query>";

            using (SPSite spSite = new SPSite(docLibraryWebSiteURL + "/"))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    SPList spList = spWeb.Lists[docLibDispName];
                    if (spList != null)
                    {
                        SPListItemCollection resourceItems = spList.GetItems(qryDocumentsByChoice);
                        if (resourceItems.Count > 0)
                            dataView = resourceItems.GetDataTable().DefaultView;
                    }
                }
            }
            return dataView;
        }
    }
}